package main

import (
	"common/erpc"
	"context"
	"fmt"
	"io"
	"io/fs"
	"os"
)

type PiecestoreServer struct {
	erpc.RpcPieceStoreServer
}

func (p *PiecestoreServer) Upload(requst erpc.UploadRequest, stream erpc.UploadStream) error {
	fmt.Println("Upload", string(requst.PieceId))
	file := "/Users/ljg/Desktop/estore333.zip"
	f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, fs.ModePerm)
	if err != nil {
		return err
	}
	defer f.Close()
	for {
		msg, readErr := stream.Recv()
		if readErr != nil {
			fmt.Println("readErr", readErr)
			return readErr
		}
		f.Write(msg.Data)
		fmt.Println(msg.Offset)
		if msg.Done == 1 {
			fmt.Println("done recv")
			break
		}
	}
	rs := &erpc.UploadResult{
		Hash: []byte("hello"),
	}
	stream.SendAndClose(rs)
	return nil
}

func (p *PiecestoreServer) Download(requst erpc.DownloadRequst, stream erpc.DownloadStream) error {
	fmt.Println("requst ", string(requst.PieceId))

	file := "/Users/ljg/Desktop/estore.zip"
	f, err := os.Open(file)
	if err != nil {
		//fmt.Println(err)
		return err
	}
	offset := 0
	buf := make([]byte, 1024)
	for {
		n, readErr := f.Read(buf)
		var done = 0
		if readErr == io.EOF {
			done = 1
			fmt.Println("done = 1")
		}
		sendErr := stream.Send(&erpc.Chunk{
			Offset: offset,
			Data:   buf[:n],
			Done:   done,
		})
		if sendErr != nil {
			fmt.Println("sendErr", sendErr)
			return sendErr
		}
		offset += n
		if readErr != nil {
			fmt.Println(readErr)
			break
		}
	}
	stream.CloseSend()
	return nil
}

func main() {
	s := &PiecestoreServer{}
	erpc.StartRpcServer(context.Background(), fmt.Sprintf(":%d", 18082), s ,false)
}
